using System.Security.Cryptography;
using System.Text;
using AntChain.AlipayUtil;

namespace Vin.Extension.Framework.AntChain.Tools;

public class AntChainTool
{
    /// <summary>
    /// ATO加密
    /// </summary>
    /// <param name="content"></param>
    /// <param name="publicKey"></param>
    /// <returns></returns>
    public static string AntChainEncrypt(string content, string publicKey)
    {
        publicKey = publicKey.Replace("-----BEGIN PUBLIC KEY-----", "").Replace("-----END PUBLIC KEY-----", "")
            .Replace("\r", "")
            .Replace("\n", "").Trim();
        var rsa = RSA.Create(2048);
        rsa.ImportSubjectPublicKeyInfo(Convert.FromBase64String(publicKey), out _);
        var data = Encoding.UTF8.GetBytes(content);
        var maxBlockSize = rsa.KeySize / 8 - 11; //加密块最大长度限制
        if (data.Length <= maxBlockSize)
        {
            var cipherbytes = rsa.Encrypt(data, RSAEncryptionPadding.Pkcs1);
            return Convert.ToBase64String(cipherbytes);
        }

        using var plaiStream = new MemoryStream(data);
        using var crypStream = new MemoryStream();
        var buffer = new byte[maxBlockSize];
        var blockSize = plaiStream.Read(buffer, 0, maxBlockSize);
        while (blockSize > 0)
        {
            var toEncrypt = new byte[blockSize];
            Array.Copy(buffer, 0, toEncrypt, 0, blockSize);
            var cryptograph = rsa.Encrypt(toEncrypt, RSAEncryptionPadding.Pkcs1);
            crypStream.Write(cryptograph, 0, cryptograph.Length);
            blockSize = plaiStream.Read(buffer, 0, maxBlockSize);
        }

        return Convert.ToBase64String(crypStream.ToArray(), Base64FormattingOptions.None);
    }

    /// <summary>
    /// 是否成功
    /// </summary>
    /// <param name="resultCode"></param>
    /// <param name="successCode"></param>
    /// <returns></returns>
    public static bool IsSuccess(string resultCode, string successCode = "")
    {
        return AntchainUtils.IsSuccess(resultCode, successCode);
    }
}